package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class simpleRedisLock implements Ilcok{
    public simpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    private StringRedisTemplate stringRedisTemplate;;
    private String name;
    private static final String LOCK_PREX = "lock:";


    @Override
    public boolean tryLock(Long timeoutSec) {
        //获取线程id
        long id = Thread.currentThread().getId();
        //创建锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREX + name, id + "", timeoutSec, TimeUnit.SECONDS);
        //返回结果
        return BooleanUtil.isTrue(success);
    }

    @Override
    public void unLock() {
        stringRedisTemplate.delete(LOCK_PREX + name);
    }
}
